package com.hfs.fence

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.amap.api.fence.GeoFence
import com.amap.api.fence.GeoFenceClient
import com.amap.api.fence.GeoFenceListener
import com.amap.api.location.DPoint

/**
 * Created by: 方燚
 * Time: 2019/5/14
 * Details:
 */
abstract class BaseActivity : AppCompatActivity() {
    /**
     * 判断本地时间是否和网络时间相同
     */
    protected var isTime = false

    /**
     * 权限返回码
     */
    private val REQ_LOCATION = 0x12

    /**
     * 围栏广播
     */
    protected var mBReceiver: MyBroadcastReceiver? = null
    protected var TAG: String? = null
    private var mGeoFenceClient: GeoFenceClient? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        applyPermission()
        super.onCreate(savedInstanceState)
        TAG = javaClass.simpleName
    }

    protected fun applyPermission() {
        if (!PermissionUtils.checkPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                REQ_LOCATION
            )
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        if (requestCode == REQ_LOCATION) {
            //                initData();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    protected fun compareTime(time: Long, netTime: Long): Boolean {
        return if (compareMin(time, netTime) > 3) {
            isTime = false
            false
        } else {
            isTime = true
            true
        }
    }

    ///    注册围栏状态广播
    protected fun registerReceiver() {
        //接受定位广播
        val filter = IntentFilter(
            ConnectivityManager.CONNECTIVITY_ACTION
        )
        filter.addAction(GEOFENCE_BROADCAST_ACTION)
        mBReceiver = MyBroadcastReceiver()
        registerReceiver(mBReceiver, filter)
    }

    //    用户进入围栏接收器
    inner class MyBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == GEOFENCE_BROADCAST_ACTION) {
                //解析广播内容
                val bundle = intent.extras
                //获取当前有触发的围栏对象：
                val fence: GeoFence? = bundle!!.getParcelable(GeoFence.BUNDLE_KEY_FENCE)
                val status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS)
                val sb = StringBuffer()
                when (status) {
                    GeoFence.STATUS_LOCFAIL -> {
                    }
                    GeoFence.STATUS_IN -> {
                        enter()
                        Log.e(TAG, "进入围栏")
                    }
                    GeoFence.STATUS_OUT -> {
                        out()
                        Log.e(TAG, "离开围栏")
                    }
                    GeoFence.STATUS_STAYED -> Log.e(TAG, "停留围栏")
                    else -> {
                    }
                }
            }
        }
    }

    //    添加圆形围栏
    fun addCircleGeoFence(
        context: Context?,
        geoFenceListener: GeoFenceListener?,
        m: Int,
        latitude: Double,
        longitude: Double
    ) {
        if (mGeoFenceClient != null) {
            mGeoFenceClient!!.removeGeoFence()
        } else {
            mGeoFenceClient = GeoFenceClient(context)
        }
        //创建一个中心点坐标
        val centerPoint = DPoint()
        //设置中心点纬度
        centerPoint.latitude = latitude
        //设置中心点经度
        centerPoint.longitude = longitude
        //执行添加围栏的操作
        mGeoFenceClient!!.addGeoFence(centerPoint, m / 2.toFloat(), "公司打卡")
        mGeoFenceClient!!.setGeoFenceListener(geoFenceListener)
        mGeoFenceClient!!.setActivateAction(GeoFenceClient.GEOFENCE_IN or GeoFenceClient.GEOFENCE_OUT or GeoFenceClient.GEOFENCE_STAYED)
        mGeoFenceClient!!.createPendingIntent(GEOFENCE_BROADCAST_ACTION)
    }

    /**
     * 添加多边形围栏
     */
    fun addPolygonGeoFence(
        context: Context?,
        geoFenceListener: GeoFenceListener?,
        points: MutableList<DPoint>
    ) {
        if (mGeoFenceClient != null) {
            mGeoFenceClient!!.removeGeoFence()
        } else {
            mGeoFenceClient = GeoFenceClient(context)
        }

        mGeoFenceClient!!.addGeoFence(points, "公司打卡")
        mGeoFenceClient!!.setGeoFenceListener(geoFenceListener)
        mGeoFenceClient!!.setActivateAction(GeoFenceClient.GEOFENCE_IN or GeoFenceClient.GEOFENCE_OUT or GeoFenceClient.GEOFENCE_STAYED)
        mGeoFenceClient!!.createPendingIntent(GEOFENCE_BROADCAST_ACTION)
    }

    protected abstract fun enter()
    protected abstract fun out()

    /**
     * 两个时间点的间隔时长（分钟）
     *
     * @param before 开始时间
     * @param after  结束时间
     * @return 两个时间点的间隔时长（分钟）
     */
    protected fun compareMin(before: Long, after: Long): Long {
        var dif: Long = 0
        dif = if (after >= before) {
            (after - before) / (1000 * 60)
            //            dif = after  - before ;
        } else {
            (before - after) / (1000 * 60)
            //            dif = after  + 86400000 - before ;
        }
        //        dif = Math.abs(dif);
//        return dif  / 60000;
        return dif
    }

    protected fun showToast(content: String) {
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show()
    }

    companion object {
        //定义接收广播的action字符串
        const val GEOFENCE_BROADCAST_ACTION = "com.demo.punch.broadcast"
    }
}